package com.hao.base.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * @author haohj
 * @date 2020-04-14 11:31
 */
public class StreamMap {
    /**
     * 取出所有的用户名字
     */
    public static void getUserNameList() {
        List<PersonModel> list = Data.getData();
        List<String> names = new ArrayList<>();
        for (PersonModel personModel : list) {
            names.add(personModel.getName());
        }
        System.out.println(names);

        List<String> collect = list.stream().map(personModel -> personModel.getName()).collect(toList());
        System.out.println(collect);

        List<String> collect1 = list.stream().map(PersonModel::getName).collect(toList());
        System.out.println(collect1);

        list.stream().map(personModel -> {
            System.out.println(personModel.getName());
            return personModel.getName();
        }).collect(toList());
    }

    public static void flatMapString() {
        List<PersonModel> data = Data.getData();
        //返回类型不一样
        List<String> collect = data.stream()
                .flatMap(person -> Arrays.stream(person.getName().split(" "))).collect(toList());
        List<Stream<String>> collect1 = data.stream()
                .map(person -> Arrays.stream(person.getName().split(" "))).collect(toList());
        System.out.println(collect);
        System.out.println(collect1);

        //用map实现
        List<String> collect2 = data.stream()
                .map(person -> person.getName().split(" "))
                .flatMap(Arrays::stream).collect(toList());
        //另一种方式
        List<String> collect3 = data.stream()
                .map(person -> person.getName().split(" "))
                .flatMap(str -> Arrays.asList(str).stream()).collect(toList());
        System.out.println(collect2);
        System.out.println(collect3);
    }

    public static void main(String[] args) {
        flatMapString();
    }
}
